package com.fuyao.cloud.personnel.api.annotaion;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class ValidationDateFormat implements ConstraintValidator<ValidationDate, String> {

    private String msg = null;

    @Override
    public void initialize(ValidationDate constraintAnnotation) {
        this.msg = String.format("时间格式错误%s", msg);
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if(StrUtil.isEmpty(value)){
            return true;
        }
        if(StrUtil.length(value) != 10 && StrUtil.length(value) != 8){
            return true;
        }
        if(!StrUtil.contains(value,"/") && !StrUtil.contains(value,"-")){
            return false;
        }
        String date = value.replaceAll("/", "-");
        try {
            DateTime dateTime = DateUtil.parse(date, DatePattern.NORM_DATE_PATTERN);
        }catch (Exception e){
            return false;
        }
        return true;
    }
}
